package com.kiragame.couplescreen.rateapp;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.preference.PreferenceManager;

public class RateApp {
	private Context context;
	private SharedPreferences store;
	private Editor editor;
	private AlertDialog.Builder builder;
	private final String SHOW_AGAIN_KEY = "dontshowagain";

	public RateApp(Context context) {
		this.context = context;
		store = PreferenceManager.getDefaultSharedPreferences(context);
		editor = store.edit();
		setUp();
	}

	private void setUp() {
		builder = new AlertDialog.Builder(context);
		String message = "If you enjoy using "
				+ getApplicationName(context)
				+ ", please take a moment to rate the app. Thank you for your support!";
		builder.setMessage(message)
				.setTitle("Rate " + getApplicationName(context))
				.setIcon(context.getApplicationInfo().icon)
				.setCancelable(false)
				.setPositiveButton("Rate Now",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								editor.putBoolean(SHOW_AGAIN_KEY, true);
								editor.commit();
								context.startActivity(new Intent(
										Intent.ACTION_VIEW,
										Uri.parse("market://details?id="
												+ context
														.getApplicationContext()
														.getPackageName())));
								dialog.dismiss();
							}
						})
				.setNeutralButton("Later",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();

							}
						});
//				.setNegativeButton("No, Thanks",
//						new DialogInterface.OnClickListener() {
//
//							@Override
//							public void onClick(DialogInterface dialog,
//									int which) {
//								if (editor != null) {
//									editor.putBoolean(SHOW_AGAIN_KEY, true);
//									editor.commit();
//								}
//								dialog.dismiss();
//
//							}
//						});
	}

	private static String getApplicationName(Context context) {
		int stringId = context.getApplicationInfo().labelRes;
		return context.getString(stringId);
	}

	public void show() {
		if (store.getBoolean(SHOW_AGAIN_KEY, false)) {
			return;
		}
		builder.show();
	}
}
